//设置系统管理员可添加、删除、修改
function initManageEvent(){
    if(isManager == 2){
        $("#btn_add").css("display","block");
        $("#btn_delete").css("display","block");
        $('#rightPartDiv').height('calc(100% - 40px)');
        $('.save_content').css("display","flex");
        $('.TxtNameContent').css("display","flex");
        var apiInfos = $('.apiDetailInfo')
        for (var i = 0; i < apiInfos.length; i++) {
            var apiInfoNode = $('#'+apiInfos[i].id);
            apiInfoNode.addClass("layui-textarea");
            apiInfoNode.attr("contenteditable","true");
        } 

        $('#btn_add').click(function(e){
            layer.open({
                type: 2,
                title: '新建目录/接口',
                shadeClose: true,
                shade: false,
                area: ['800px', '480px'],
                content: '/BasePlatform/Home/developmentCenter.html', //iframe的url
                btn: ['确定', '取消','重置'],
                maxmin: true, //开启最大化最小化按钮
                btn1: function(index, layero) {
                    var iframe = window['layui-layer-iframe' + index];
                    var resData = iframe.$("[name='btn_creat']").click();
                    if(resData != false){
                        data = resData;
                        layer.closeAll(); 
                        layer.msg('添加成功', {icon: 1,time: 1000,shade : [0.5 , '#000' , true]});
                        initLeftTree(); 
                    } 

                },
                btn2: function(index, layero) {
                    layer.close(index);
                },
                btn3: function(index, layero) {
                    var iframe = window['layui-layer-iframe' + index];
                    iframe.$("[name='btn_reset']").click();
                    return false;
                },
                success:function (layero,index) {
                    var iframe = window['layui-layer-iframe' + index];
                    iframe.$("[name='submit-form-item']").css("display","none");
                }
            });
        });
        $('#btn_delete').click(function(e){
            layui.layer.confirm('确认删除吗？', {
                btn: ['确认', "取消"]
            }, function(index, layero) { 
                let id = $('.layui-this a').attr('data-id')
                var results = sendAjax(modelURL + "resource/deleteDevelopmentById", "POST", {
                    id
                });
                if (results.code == 200) {
                    data = getMenuData();
                    initLeftTree();
                    layer.msg("删除成功",{icon:1})
                }else{
                    layer.msg("删除失败",{icon:5})
                }
                layui.layer.close(index);
            }, function(index) {
                layui.layer.close(index);
            });
        });
        $('#btn_update').click(function(e){
            var attrTableParam = '';
            if(attrTableCache.length>0){
                attrTableParam = attrTableCache;
                for(var i = 0;i<attrTableParam.length;i++){
                    delete attrTableParam[i].LAY_TABLE_INDEX;
                }
                attrTableParam = JSON.stringify(attrTableParam)
            }
            var obj = {
                name:$('#name').text()==""?$("#btn_update").attr("attrName"):$('#name').text(),
                type:$('#type').text(),
                description:$('#description').text(),
                call:$('#call').text(),
                inputvalue:attrTableParam,
                returnvalue:$('#returnvalue').text(),
                codeexample:$('#codeexample').text(),
                ismenu:"0",
                pid:$("#btn_update").attr("attrPid"),
                id:$("#btn_update").attr("attrId")
            }
            var results = sendAjax(modelURL + "resource/updateDevelopmentCenter", "POST",obj);
            if (results.code == 200) {
                layer.msg("修改成功",{icon:1})
            }else{
                layer.msg("修改失败",{icon:5})
            }
        });
    }
}
//获取左侧目录树数据
function getMenuData(){
    var results = null;
    if (portaluserno != '') {
        $.ajax({
            type: "post",
            async: false,
            url: modelURL + "resource/getDevelopmentCenterMenu",
            data: {},
            success: function(res) {
                var res = JSON.parse(res)
                // 判断状态码等于200 和 有这个
                if (res.code == 200 ) {
                    res.data.sort(compare('id')); 
                    results = res.data; // treedata 表的数据
                } else {
                    layer.msg("获取数据失败！",{icon:5});
                }
            },
            error: function(err) {}
        });
    } else {
        location.href = '/'
    }
    return results;
}
function initLeftTree(){
    var liStr= "", isFirstTime = true;
    // 遍历生成主菜单 
    let data = getMenuData();
    for( var i = 0; i <data.length; i++){
        // 判断是否存在子菜单
        if(data[i].children!=null&&data[i].children.length>0){
            
            if(isFirstTime){
                liStr+="<li class=\"layui-nav-item layui-nav-itemed treeParentNode\">"
                + "<a class=\"treeParentNodeA\" href=\"javascript:;\"><img src=\"../../../img/BasePlatform/mineResource/firstLevel.png\"/>&nbsp&nbsp"+treedata[i].name+"</a>\n"
                + "<dl class=\"layui-nav-child\">\n";
                // 遍历获取子菜单
                for( var k = 0; k <data[i].children.length; k++){
                    if(k == 0){
                        liStr+= getFirstChildMenu(data[i].children[k],0);
                    }else{
                        liStr+=getChildMenu(data[i].children[k],0);
                    }
                }
                isFirstTime = false;
            }else{
                liStr+="<li class=\"layui-nav-item\"><a class=\"\" href=\"javascript:;\"><img src=\"../../../img/BasePlatform/mineResource/firstLevel.png\"/>&nbsp&nbsp"+data[i].name+"</a>\n"+
                        "<dl class=\"layui-nav-child\">\n";
                for( var k = 0; k <data[i].children.length; k++){
                    liStr+=getChildMenu(data[i].children[k],0);
                }
            }
            liStr+="</dl></li>";
        }else{
            liStr+="<li class=\"layui-nav-item\"><a class=\"\" href=\"javascript:;\" data-id=\""+data[i].id+"\" data-pid=\""+data[i].pid+"\" data-name=\""+data[i].name+"\"><img src=\"../../../img/BasePlatform/mineResource/firstLevel.png\"/>&nbsp&nbsp "+data[i].name+"</a></li>";
        }
    };
    $(".navUL").html(liStr);
    element.render("nav");
    if(firstMenuId != ""){
        initRightContent(firstMenuId,firstMenuPid,firstMenuName);
    };
    $(".treeNodeA").click(function(e){
        var thisId = $(this).attr("data-id");
        var thisPid = $(this).attr("data-pid");
        var thisName = $(this).attr("data-name");
        if(typeof(thisId) != "undefined"){
            initRightContent(thisId,thisPid,thisName);
        }
    });
}
var FirstChildTime = true;
// 第一次递归生成子菜单
function getFirstChildMenu(subMenu,num) {
    num++;
    var subStr = "";
    if(subMenu.children!=null&&subMenu.children.length>0){
        subStr+="<dd><ul><li class=\"layui-nav-item layui-nav-itemed\" ><a style=\"padding-left: "+num*menuCell+"em\"  class=\"\" href=\"javascript:;\">&nbsp&nbsp<img src=\"../../../img/BasePlatform/mineResource/nextLevel.png\"/>&nbsp&nbsp"+subMenu.name+"</a>" +
        "<dl class=\"layui-nav-child\">\n";
        for( var j = 0; j <subMenu.children.length; j++){
            subStr+=getFirstChildMenu(subMenu.children[j],num);
        }
        subStr+="</dl></li></ul></dd>";
    }else{
        if(subMenu.ismenu == "0"){
            if(FirstChildTime){
                subStr+="<dd class = \"layui-this\"><a class = \"treeNodeA\"  style=\"padding-left: "+num*menuCell+"em\" href=\"javascript:;\" data-id=\""+subMenu.id+"\" data-pid=\""+subMenu.pid+"\" data-name=\""+subMenu.name+"\">&nbsp&nbsp<img src=\"../../../img/BasePlatform/mineResource/lastLevel.png\"/>&nbsp&nbsp"+subMenu.name+"</a></dd>";
                firstMenuId = subMenu.id;
                firstMenuPid = subMenu.pid;
                firstMenuName = subMenu.name;
                FirstChildTime = false;
            }else{
                subStr+="<dd><a class = \"treeNodeA\" style=\"padding-left: "+num*menuCell+"em\" href=\"javascript:;\" data-id=\""+subMenu.id+"\" data-pid=\""+subMenu.pid+"\" data-name=\""+subMenu.name+"\">&nbsp&nbsp<img src=\"../../../img/BasePlatform/mineResource/lastLevel.png\"/>&nbsp&nbsp"+subMenu.name+"</a></dd>";
            }
        }else{
            subStr+="<dd><a style=\"padding-left: "+num*menuCell+"em\" href=\"javascript:;\" data-id=\""+subMenu.id+"\" data-pid=\""+subMenu.pid+"\" data-name=\""+subMenu.name+"\">&nbsp&nbsp<img src=\"../../../img/BasePlatform/mineResource/nextLevel.png\"/>&nbsp&nbsp"+subMenu.name+"</a></dd>";
        }
    }
    return subStr;
}
// 递归生成子菜单
function getChildMenu(subMenu,num) {
    num++;
    var subStr = "";
    if(subMenu.children!=null&&subMenu.children.length>0){
        subStr+="<dd><ul><li class=\"layui-nav-item\" ><a style=\"padding-left: "+num*menuCell+"em\"  class=\"\" href=\"javascript:;\">&nbsp&nbsp<img src=\"../../../img/BasePlatform/mineResource/nextLevel.png\"/>&nbsp&nbsp"+subMenu.name+"</a>" +
        "<dl class=\"layui-nav-child\">\n";
        for( var j = 0; j <subMenu.children.length; j++){
            subStr+=getChildMenu(subMenu.children[j],num);
        }
        subStr+="</dl></li></ul></dd>";
    }else{
        if(subMenu.ismenu == 0){
            subStr+="<dd><a class = \"treeNodeA\" style=\"padding-left: "+num*menuCell+"em\" href=\"javascript:;\" data-id=\""+subMenu.id+"\" data-pid=\""+subMenu.pid+"\" data-name=\""+subMenu.name+"\">&nbsp&nbsp<img src=\"../../../img/BasePlatform/mineResource/lastLevel.png\"/>&nbsp&nbsp"+subMenu.name+"</a></dd>";
        }else{
            subStr+="<dd><ul><li class=\"layui-nav-item\" ><a style=\"padding-left: "+num*menuCell+"em\" href=\"javascript:;\" data-id=\""+subMenu.id+"\" data-pid=\""+subMenu.pid+"\" data-name=\""+subMenu.name+"\">&nbsp&nbsp<img src=\"../../../img/BasePlatform/mineResource/nextLevel.png\"/>&nbsp&nbsp"+subMenu.name+"</a></li></ul></dd>";
        }
        // subStr+="<dd><a style=\"text-indent:"+num*menuCell+"em\" href=\"javascript:;\" data-url=\""+subMenu.url+"\"><i class='layui-icon "+ subMenu.icon +"'></i> "+subMenu.name+"</a></dd>";
    }
    return subStr;
}
//填充右侧内容
function initRightContent(thisId,thisPid,thisName){
    $('#btn_delete').attr("attrId",thisId);
    $('#btn_delete').attr("attrPid",thisPid);
    $('#btn_delete').attr("attrName",thisName);

    $('#btn_update').attr("attrId",thisId);
    $('#btn_update').attr("attrPid",thisPid);
    $('#btn_update').attr("attrName",thisName);
    getDetailById(thisId);
}
//初始化右侧表格数据
function initTable(requestData) {
    var cols; 
    if(isManager == 2){
        cols = [[
            { field: 'name', title: '参数名称', align: 'center',edit:'text' }
            , { field: 'meaning', title: '参数含义', align: 'center',edit:'text' }
            , { field: 'type', title: '字段类型', align: 'center',edit:'text' }
            , { field: 'require', title: '是否必须', align: 'center',edit:'text' }
            , { field: 'comments', title: '备注', align: 'center',edit:'text' }
        ]];
    }else{
        cols = [[
            { field: 'name', title: '参数名称', align: 'center' }
            , { field: 'meaning', title: '参数含义', align: 'center' }
            , { field: 'type', title: '字段类型', align: 'center' }
            , { field: 'require', title: '是否必须', align: 'center' }
            , { field: 'comments', title: '备注', align: 'center' }
        ]];
    }
    
    table.render({
        elem: '#requestParamsTable'
        , data: requestData
        , toolbar: false
        , cols: cols
        , page: false
        , response: {
            statusCode: 200 //重新规定成功的状态码为 200，table 组件默认为 0
        }
        , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            return {
                "code": res.status, //解析接口状态
                "msg": res.message, //解析提示文本
                "count": res.total, //解析数据长度
                "data": res.rows.item //解析数据列表
            };
        }
        ,done: function(res, curr, count) {
            attrTableCache = layui.table.cache['requestParamsTable'];
        }
    });
}
//根据id查询右侧内容
function getDetailById(id){
    var results = null;
    if (portaluserno != '') {
        $.ajax({
            type: "post",
            async: false,
            url: modelURL + "resource/getDevelopmentCenterDetailsById",
            data: {
                id:id
            },
            //$('#rightPartDiv').css("display","block");
            success: function(res) {
                var res = JSON.parse(res)
                // 判断状态码等于200 和 有这个
                if (res.code == 200 ) {
                    // res.data.sort(compare('id')); 
                    results = res.data;
                    initDetailInfo(results)
                    $('#rightPartDiv').css("display","block");
                } else {
                    layer.msg("获取数据失败！",{icon:5});
                }
            },
            error: function(err) {}
        });
    } else {
        location.href = '/'
    }
    return results;
}
//初始化右侧内容
function initDetailInfo(data){
    $('.apiDetailInfo').text("");
    $('#name').text(data.name);
    $('#description').text(data.description);
    $('#type').text(data.type);
    $('#call').text(data.call);
    $('#returnvalue').text(data.returnvalue);
    $('#codeexample').text(data.codeexample);
    if(data.requesttype != undefined){
        $('#requesttype').text(data.requesttype==""?"GET":data.requesttype);
    }
    var requestParams="";
    var resStr = data.inputvalue;
    if(resStr!=""){
        requestParams = JSON.parse(resStr);
    }
    initTable(requestParams);
}
//获取登录用户身份
function getUserRole(){
    // （0  普通用户  1   部门管理员   2  系统管理员）
    var results = sendAjax(modelURL + "user/getUserIsManager", "POST", {
        userNo:portaluserno
    });
    if (results.code == 200) {
        return results.data.ISMANAGER
    } else {
        return null;
    }
}